<?php
class db {
	private $conn;
	private $conn_s;
	private $query;
	private $connectType;
	private $db;

	public function __construct ($connectType='ureadme') {
		global $defineDB;
		$this->connectType = $connectType;
		if ($defineDB[$connectType]) {
			$this->db = $defineDB[$connectType];
		} else {
			die('No Defined DB');
		}
		// 连接主库
		$conn = mysql_connect($this->db['dbhost'], $this->db['dbuser'], $this->db['dbpass']);
		if ($conn) {
			mysql_select_db($this->db['dbname'], $conn);
			mysql_query('SET NAMES UTF8');
			$this->conn = $conn;
		} else die('can not connect master');
		// 连接主库
		if ($this->db['dbhost_s']) {
			$conn = mysql_connect($this->db['dbhost_s'], $this->db['dbuser'], $this->db['dbpass']);
			if ($conn) {
				mysql_select_db($this->db['dbname'], $conn);
				mysql_query('SET NAMES UTF8');
				$this->conn_s = $conn;
			} else die('can not connect slave');
		}
	}
	public function execute ($sql) {
		$sql = trim($sql);
		if (preg_match("/^INSERT/i",$sql)) {
			if (mysql_query($sql, $this->conn)) {
				return mysql_insert_id($this->conn);					// 返回insert_id
			} else return false;
		} elseif (preg_match("/^(DELETE|UPDATE|REPLACE|DROP|CREATE|ALERT)/i", $sql)) {
			if (mysql_query($sql, $this->conn)) {
				return mysql_affected_rows($this->conn);				// 返回affected rows
			} else return false;
		} elseif (preg_match("/^(SELECT|SHOW|DESCRIBE|EXPLAIN)/i", $sql)) {
			if ($this->conn_s) {
				$query = mysql_query($sql, $this->conn_s);
			} else {
				$query = mysql_query($sql, $this->conn);
			}
			if ($query) {
				while ($fetch = mysql_fetch_assoc($query)) {
					$array[]	=	$fetch;
				}
			}
			return  (is_array($array)) ? $array : false;
		} else {
			return false;
		}
	}
}
?>